<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData">
			<el-row :gutter="15">
				<el-col :xs="24" :lg="8" class="mb15">
					<el-form-item ref="Name_FormItem" prop="Name">
						<template #label>
							<WtmLabelTooltip label="班次名称" tooltip="考勤班次规则的显示名称" />
						</template>
						<el-input v-model="searchData.Name" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :lg="8" class="mb15">
					<el-form-item ref="IsEnabled_FormItem" prop="IsEnabled">
						<template #label>
							<WtmLabelTooltip label="是否启用" tooltip="班次规则是否生效" />
						</template>
						<el-select v-model="searchData.IsEnabled" clearable>
							<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
							<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysAttendanceShift/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceShift/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceShift/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceShift/SysAttendanceShiftExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysAttendanceShift/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysAttendanceShift/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysAttendanceShift/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="班次管理;true;HengTong.Areas.Hr.Controllers;SysAttendanceShift">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysAttendanceShiftApi as api } from '/@/views/hr/sysattendanceshift/api';
import { ISysAttendanceShiftView, ISysAttendanceShiftQuery } from '/@/views/hr/sysattendanceshift/api/interface';
import other from '/@/utils/other';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysAttendanceShiftQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({});

const searchData = ref<ISysAttendanceShiftQuery>({
	Name: null,
	IsEnabled: null,
	Order: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		// 基础信息 - 最高优先级
		{ title: '班次名称', key: 'Name', type: 'text', isCheck: true },
		{ title: '状态', key: 'IsEnabled', type: 'switch', isCheck: true },
		{ title: '是否默认', key: 'IsDefault', type: 'switch', isCheck: true },
		{ title: '排序', key: 'Order', type: 'text', isCheck: true },
		{ title: '标签', key: 'Tag', type: 'text', isCheck: true },
		{ title: '颜色', key: 'DisplayColor', type: 'text', isCheck: true },

		// 核心工作时间 - 高优先级
		{ title: '上班时间', key: 'WorkStartTime', type: 'text', isCheck: true },
		{ title: '下班时间', key: 'WorkEndTime', type: 'text', isCheck: true },
		{ title: '标准工时', key: 'StandardWorkMinutes', type: 'text', isCheck: true },
		{ title: '出勤天数', key: 'AttendanceDays', type: 'text', isCheck: true },

		// 打卡时间设置 - 中等优先级
		{ title: '上班打卡开始', key: 'WorkStartPunchStartTime', type: 'text', isCheck: true },
		{ title: '上班打卡结束', key: 'WorkStartPunchEndTime', type: 'text', isCheck: true },
		{ title: '下班打卡开始', key: 'WorkEndPunchStartTime', type: 'text', isCheck: true },
		{ title: '下班打卡结束', key: 'WorkEndPunchEndTime', type: 'text', isCheck: true },

		// 违规规则 - 中等优先级
		{ title: '违规规则', key: 'AttendanceViolationRuleEnabled', type: 'switch', isCheck: true },
		{ title: '迟到阈值', key: 'LateMinutesThreshold', type: 'text', isCheck: true },
		{ title: '早退阈值', key: 'EarlyLeaveMinutesThreshold', type: 'text', isCheck: true },
		{ title: '迟到旷工阈值', key: 'AbsenceByLateMinutesThreshold', type: 'text', isCheck: true },
		{ title: '早退旷工阈值', key: 'AbsenceByEarlyLeaveMinutesThreshold', type: 'text', isCheck: true },
		{ title: '偏差旷工阈值', key: 'AbsenceByTotalDeviationMinutesThreshold', type: 'text', isCheck: true },

		// 补贴和排班 - 较低优先级
		{ title: '补贴规则', key: 'SubsidyRuleEnabled', type: 'switch', isCheck: false },
		{ title: '补贴规则列表', key: 'SubsidyRulesName', type: 'text', isCheck: false },
		{ title: '假日排班', key: 'IsHolidayScheduled', type: 'switch', isCheck: true },
		{ title: '工作日', key: 'WorkDays', type: 'text', isCheck: false },

		// 详细设置 - 最低优先级
		{ title: '上班基准日', key: 'WorkStartDayOffset', type: 'text', isCheck: true },
		{ title: '下班基准日', key: 'WorkEndDayOffset', type: 'text', isCheck: true },
		{ title: '上班打卡开始基准日', key: 'WorkStartPunchStartDayOffset', type: 'text', isCheck: true },
		{ title: '上班打卡结束基准日', key: 'WorkStartPunchEndDayOffset', type: 'text', isCheck: true },
		{ title: '下班打卡开始基准日', key: 'WorkEndPunchStartDayOffset', type: 'text', isCheck: true },
		{ title: '下班打卡结束基准日', key: 'WorkEndPunchEndDayOffset', type: 'text', isCheck: true },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysAttendanceShiftView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysAttendanceShiftView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysAttendanceShiftView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysAttendanceShiftView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [getTableData()];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
